<template>
  <div>
    <div>
      <el-tag @click="handleAdd()">新增</el-tag>
    </div>
    <el-table
      empty-text="暂无数据"
      slot="empty"
      type="expand"
      :data="
        tableData.filter(
          (data) =>
            !search || data.name.toLowerCase().includes(search.toLowerCase())
        )
      "
      style="width: 100%"
    >
      <el-table-column label="编号" prop="aid" width="50"></el-table-column>

      <el-table-column label="景区名称" prop="aname"></el-table-column>

      <el-table-column label="景区地址" prop="addr"></el-table-column>

      <el-table-column label="简介" prop="desc"></el-table-column>

      <el-table-column label="介绍" width="120">
        <template slot-scope="scope">
          <span style="margin-left: 10px">
            <el-button type="text" @click="openBox(scope.row.detail)">点击查看</el-button>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" width="160">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.refreshTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="等级">
        <template slot-scope="scope">
          <el-rate
            v-model="scope.row.grade"
            show-scoreFf
            text-color="#ff9900"
            show-score
            score-template="{value}"
            @change="changeGrade(scope.row)">
          </el-rate>
        </template>
      </el-table-column>

      <el-table-column label="票价" prop="price" width="50"></el-table-column>

      <el-table-column prop="status" label="下架/上架" width="80">
        <template slot-scope="scope">
          <el-tooltip
            :content="scope.row.aname+'当前状态:'+scope.row.status"
            placement="top">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="正常"
              inactive-value="下架"
              @change="stateChange(scope.row)">
            </el-switch>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column align="right" width="150">
        <template slot="header">
          <!-- slot-scope="scope" -->
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索"/>
        </template>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
          >编辑
          </el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block" align="center" style="margin-top:25px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 修改的模态框 -->
    <el-dialog title="修改景区信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="图片" :label-width="formLabelWidth">
          <div class="block">
            <el-image
              style="width: 240px; height: 135px"
              :src="form.apic1"
              fit="fit"
              alt="暂无图片，上传一个吧"
            ></el-image>
            <el-image
              style="width: 240px; height: 135px"
              :src="form.apic2"
              fit="fit"
            ></el-image>
            <el-image
              style="width: 240px; height: 135px"
              :src="form.apic3"
              fit="fit"
            ></el-image>
          </div>
        </el-form-item>

        <el-form-item
          label="上传图片"
          :label-width="addformLabelWidth"
          prop="detail"
        >
          <el-upload
            list-type="picture-card"
            :auto-upload="false"
            :on-change="checkImageType"
            :limit="3"
          >
            <!-- accept="image/jpeg,image/png,image/jpg,image/PNG" -->
            <!-- 接受的格式 -->
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                fit="fit"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="form.dialogImageUrl" alt=""/>
          </el-dialog>
        </el-form-item>

        <el-form-item
          label="景区名称"
          :label-width="formLabelWidth"
          prop="aname"
        >
          <el-input v-model="form.aname" placeholder="请输入景区名"></el-input>
        </el-form-item>

        <el-form-item label="地址" :label-width="formLabelWidth" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入地址"></el-input>
        </el-form-item>

        <el-form-item label="简介" :label-width="formLabelWidth" prop="desc">
          <el-input v-model="form.desc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="等级" :label-width="formLabelWidth" prop="grade">
          <div style="margin-top: 10px">
            <el-rate v-model="form.grade"></el-rate>
          </div>
        </el-form-item>

        <el-form-item label="价格" :label-width="formLabelWidth" prop="price">
          <el-input
            type="number"
            v-model="form.price"
            autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-tooltip :content="'当前景区状态: ' + form.status" placement="top">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#dcdfe6"
              active-value="正常"
              inactive-value="下架"
            >
            </el-switch>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="详情" :label-width="formLabelWidth" prop="detail">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入景区详情"
            v-model="form.detail">
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateArea()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 增加的模态框 -->
    <el-dialog title="景区信息添加" :visible.sync="adddialogFormVisible">
      <el-form :model="addform" :rules="rules">
        <el-form-item
          label="景区名称"
          :label-width="addformLabelWidth"
          prop="aname"
        >
          <el-input
            v-model="addform.aname"
            placeholder="请输入景区名"
          ></el-input>
        </el-form-item>

        <el-form-item label="地址" :label-width="addformLabelWidth" prop="addr">
          <el-input v-model="addform.addr" placeholder="请输入地址"></el-input>
        </el-form-item>

        <el-form-item label="简介" :label-width="addformLabelWidth" prop="desc">
          <el-input v-model="addform.desc" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="等级"
          :label-width="addformLabelWidth"
          prop="grade"
        >
          <div style="margin-top: 10px">
            <el-rate v-model="addform.grade"></el-rate>
          </div>
        </el-form-item>

        <el-form-item
          label="价格"
          :label-width="addformLabelWidth"
          prop="price"
        >
          <el-input
            type="number"
            v-model="addform.price"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="状态"
          :label-width="addformLabelWidth"
          prop="status"
        >
          <el-tooltip
            :content="'当前景区状态: ' + addform.status"
            placement="top"
          >
            <el-switch
              v-model="addform.status"
              active-color="#13ce66"
              inactive-color="#dcdfe6"
              active-value="正常"
              inactive-value="下架"
            >
            </el-switch>
          </el-tooltip>
        </el-form-item>

        <el-form-item
          label="详情"
          :label-width="addformLabelWidth"
          prop="detail"
        >
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入景区详情"
            v-model="addform.detail"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adddialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addArea()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [
        {
          aid: 1,
          aname: "秦始皇帝陵博物院",
          addr: "陕西省西安市临潼区",
          apic1: null,
          apic2: null,
          apic3: null,
          desc: "世界八大奇迹之一",
          detail:
            "秦始皇兵马俑可以说是西安旅游的名片了，因其规模之震撼气势之恢弘被列为世界第一大奇迹，是西安旅游必去的十大景点之首，可以说没有去看过兵马俑就不算来过西安。建议游玩的时候请一个讲解员，边游览边了解历史背景和故事，会带给你永生难忘的记忆。",
          grade: 5,
          price: 150,
          refreshTime: "2022-03-11T12:30:58.000+0000",
          status: "正常",
        },
      ],
      search: "",
      multipleSelection: [],
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {
        dialogImageUrl: "",
        file: "",
      },
      adddialogFormVisible: false,
      addformLabelWidth: "120px",
      addform: {
        aid: 1,
        aname: "秦始皇帝陵博物院",
        addr: "陕西省西安市临潼区",
        desc: "世界八大奇迹之一",
        detail:
          "秦始皇兵马俑可以说是西安旅游的名片了，因其规模之震撼气势之恢弘被列为世界第一大奇迹，是西安旅游必去的十大景点之首，可以说没有去看过兵马俑就不算来过西安。建议游玩的时候请一个讲解员，边游览边了解历史背景和故事，会带给你永生难忘的记忆。",
        grade: 5,
        price: 150,
        status: "正常",
        apic1: null,
        apic2: null,
        apic3: null,
      },
      dialogVisible: false,
      disabled: false,
      rules: {
        uname: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 4, max: 6, message: "长度在 4 到 6 个字符", trigger: "blur"},
        ],
        stateCode: [{required: true, message: "请选择状态", tigger: "blur"}],
        realName: [
          {required: true, message: "请输入真实姓名", trigger: "blur"},
          {min: 2, max: 5, message: "长度在 5 到 5 个字符", trigger: "blur"},
        ],
      },
      currentPage: 1,
      pageSize: 5,
      total: 100,
    };
  },
  created: function () {
    //页面用户列表初始化
    this.$axios
      .get("areas")
      .then((res) => {
        if (res.data.statusCode == 200) {
          this.tableData = res.data.info;
          this.total = res.data.countInfo;
        }
      })
      .catch((error) => {
        console.log(error);
      });
  },
  methods: {
    handleEdit(index, row) {
      console.log(index, row);
      this.form = row;
      this.form.index = index;

      this.dialogFormVisible = true;
    },

    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm(
        "此操作将永久删除" + row.aname + "的信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$axios
            .delete("deleteArea?aid=" + row.aid)
            .then((res) => {
              if (res.data.statusCode == 200) {
                //更新表单???
                console.log(res.data.msg);
                this.tableData.splice(index, 1);
                this.$message({message: "删除成功", type: "success"});
              } else {
                this.$message.error("删除失败");
              }
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleAdd() {
      this.adddialogFormVisible = true;
    },

    updateArea: function () {
      //使用axios向后端发出put请求
      this.$axios
        .put("updateArea", this.form)
        .then((res) => {
          if (res.data.statusCode == 200) {
            //更新表单???
            console.log(res.data.msg);
            this.dialogFormVisible = false;
            this.$message({message: "修改景区成功", type: "success"});
          } else {
            this.$message.error("修改景区失败");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    addArea: function () {
      this.$axios
        .post("addArea", this.addform)
        .then((res) => {
          if (res.data.statusCode == 200) {
            //更新表单???
            console.log(res.data.msg);
            this.tableData.push(res.data.info);
            this.adddialogFormVisible = false;
            this.$message({message: "添加景区成功", type: "success"});
          } else {
            this.$message.error("添加景区失败");
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.addform.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    stateChange(row) {
      // console.log(row);
      // console.log(code);
      // console.log( row.state.statusText);
      // console.log(index);
      this.$axios
        .put("changeAreaState", {
          aid: row.aid,
          status: row.status,
        })
        .then((res) => {
          if (res.data.statusCode == 200) {
            this.$message({
              message:
                row.aname + "成功修改为" + row.status + "状态",
                type: "success",
            });
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("修改异常，即将刷新！");
          setTimeout(() => {
            //location.reload();
          }, 2000);
        });
    },
    async checkImageType(file, filters) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      //alert(fileType);
      filters = [];
      if (fileType != "jpeg" && fileType != "jpg" && fileType != "png") {
        this.$message.error("图片格式不正确");
        return false;
      }
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error("图片大小不能超过2M");
        return false;
      }
      this.form.file = file;
      let formData = new FormData();
      formData.append("pic", this.form.file.raw);
      formData.append("areaId", this.form.aid);
      console.log("FILE:" + formData);
      const {data: res} = await this.$axios.post("addAreaPic", formData);
      if (res.statusCode == 200) {
        this.$message({message: "图片上传成功", type: "success"});
        //location.reload();
        this.$axios
          .get("areas")
          .then((res) => {
            if (res.data.statusCode == 200) {
              this.tableData = res.data.info;
            }
          })
          .catch((error) => {
            console.log(error);
          });
      } else {
        this.$message.error("图片上传失败");
      }
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.$axios
        .get("areas?page=" + this.currentPage + "&pageSize=" + this.pageSize)
        .then((res) => {
          if (res.data.statusCode == 200) {
            this.tableData = res.data.info;
            this.total = res.data.countInfo;
          }
        })
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.$axios
        .get("areas?page=" + this.currentPage + "&pageSize=" + this.pageSize)
        .then((res) => {
          if (res.data.statusCode == 200) {
            this.tableData = res.data.info;
            this.total = res.data.countInfo;
          }
        });
    },
    openBox(val){
      this.$alert(val, '景区介绍', {
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${ action }`
          });
        }
      });
    },
    changeGrade(row){
      this.$axios
        .put("updateAreae", {
          aid: row.aid,
          status: row.grade,
        })
        .then((res) => {
          if (res.data.statusCode == 200) {
            this.$message({
              message: row.aname + "成功修改为" + row.grade + "分",
              type: "success",
            });
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("修改异常，即将刷新！");
          setTimeout(() => {
            //location.reload();
          }, 2000);
        });
    }
  },
};
</script>
<style scoped>
</style>
